
package com.insigma.business.qrcode.soldier._bff.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.insigma.business.common.dto.CurrentUser;
import com.insigma.business.common.utils.CurrentUserUtil;
import com.insigma.business.qrcode.common.util.*;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.common.vo.SessionSoldier;
import com.insigma.business.qrcode.soldier.entity.SoldierOuterLoginAccountDO;
import com.insigma.business.qrcode.soldier.request.SoldierOuterLoginAccountUpdateRequest;
import com.insigma.business.qrcode.soldier.service.CacheClient;

import com.insigma.business.qrcode.common.vo.UserTypeEnum;
import com.insigma.business.qrcode.soldier.dto.SoldierDTO;
import com.insigma.business.qrcode.soldier.dto.SoldierOuterLoginAccountDTO;
import com.insigma.business.qrcode.soldier.dto.gov.BaseProviderImpl;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import com.insigma.business.qrcode.soldier.request.BaseApiRequest;
import com.insigma.business.qrcode.soldier.request.BaseGetRequest;
import com.insigma.business.qrcode.common.dto.ErrorCodeEnum;
import com.insigma.business.qrcode.soldier._bff.SoldierBffProvider;
import com.insigma.business.qrcode.soldier._consumer.SoldierConsumer;
import com.insigma.business.qrcode.soldier.service.SoldierOuterLoginAccountService;
import com.insigma.business.qrcode.soldier.service.impl.SoldierResponseFilter;
import com.insigma.business.qrcode.soldier.util.BizCheckUtils;
import com.insigma.business.qrcode.welfare.dto.SoldierUserInfoDTO;
import com.insigma.business.qrcode.merchant._consumer.CareWelfareMerchantInfoConsumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Slf4j
@Service
@Component("soldierBffProvider")
public class SoldierBffProviderImpl extends BaseProviderImpl implements SoldierBffProvider {

    @Autowired
    private SoldierConsumer soldierConsumer;

    @Autowired
    private SoldierOuterLoginAccountService soldierOuterLoginAccountService;

    @Autowired
    @Qualifier(value = "mysqlCacheClient")
    private CacheClient cacheClient;

    @Autowired
    private CareWelfareMerchantInfoConsumer careWelfareMerchantInfoConsumer;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public BaseResponse<Integer> changeProfilePic(final SoldierOuterLoginAccountUpdateRequest updateRequest) {
        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotBlank(updateRequest.getProfilePicture(), "图片路径不能为空！");
                BizCheckUtil.checkNotBlank(updateRequest.getOpenid(), "用户id不能为空！");
            }
            @Override
            public void executeService() {
                SoldierOuterLoginAccountDO soldierOuterLoginAccountDO = soldierOuterLoginAccountService.getByOuterSysTypeAndUserId(1,updateRequest.getOpenid());
                BizCheckUtil.checkNotNull(soldierOuterLoginAccountDO, "未获取到用户注册信息！");
                soldierOuterLoginAccountDO.setOuterSysAvatarUrl(updateRequest.getProfilePicture());
                CurrentUser currentUser = CurrentUserUtil.getCurrentUser();
                soldierOuterLoginAccountDO.setModifierId(currentUser.getUserId());
                soldierOuterLoginAccountDO.setModifyDatetime(new Date());
                Integer i = soldierOuterLoginAccountService.update(soldierOuterLoginAccountDO);
                ResponseUtil.setupSuccessResponse(baseResponse, i);
            }
            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.COMMON_SOLDIER_PROFILE_PICTURE_UPDATE;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<JSONObject> getSoldier(final BaseGetRequest baseGetRequest) {

        final BaseResponse<JSONObject> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(baseGetRequest, "获取单条Soldier的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String) baseGetRequest.getId(), "id不能为空");
            }

            @Override
            public void executeService() {
                final BaseResponse<SoldierDTO> soldierResponse = soldierConsumer.getSoldier(baseGetRequest);
                final JSONObject jsonObject = SoldierResponseFilter.filterGet(soldierResponse.getDto());
                ResponseUtil.setupResponseOfJSONObj(baseResponse, soldierResponse, jsonObject);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_GET;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<SoldierUserInfoDTO> checkSshUserInfo(final BaseApiRequest request) {
        SessionSoldier sessionSoldier = RpcContextUtil.getSessionSoldier();
        return soldierConsumer.checkSshUserInfo(sessionSoldier.getUserId());
//        return ResponseUtils.buildSuccessResponse(CurrentUserUtil.getCurrentUser());

    }

    @Override
    public BaseResponse<SoldierUserInfoDTO> getSoldierDetailBySoldierId(BaseApiRequest request) {
        return soldierConsumer.checkSshUserInfo(request.getSoldierId());
    }

    @Override
    public BaseResponse<List<SoldierUserInfoDTO>> querySoldierRelationshipList(BaseApiRequest request) {
        SessionSoldier sessionSoldier = RpcContextUtil.getSessionSoldier();
        return soldierConsumer.querySoldierRelationshipList(sessionSoldier.getUserId());
    }

    @Override
    public BaseResponse<SoldierUserInfoDTO> checkSshUserInfoOldQrString() {
        SessionSoldier sessionSoldier = RpcContextUtil.getSessionSoldier();
        return soldierConsumer.checkSshUserInfoOldQrString(sessionSoldier.getUserId());
    }

    @Override
    public BaseResponse<SoldierUserInfoDTO> checkLbmInfo(BaseApiRequest request) {
        SessionSoldier sessionSoldier = RpcContextUtil.getSessionSoldier();
        BizCheckUtil.checkNotNull(sessionSoldier, "您还未获得老兵码");
        return soldierConsumer.checkLbmInfo(sessionSoldier.getUserId());
    }

    @Override
    public BaseResponse<SoldierUserInfoDTO> getSoldierBasicInfoByQr(BaseApiRequest request) {
        return null;
    }

    @Override
    public BaseResponse<SoldierUserInfoDTO> querySoldierDetail(final BaseApiRequest request) {
        SessionSoldier sessionSoldier = RpcContextUtil.getSessionSoldier();
        BizCheckUtil.checkNotNull(sessionSoldier, "用户非法");
        return soldierConsumer.querySoldierDetail(sessionSoldier.getUserId());
    }

    @Override
    public BaseResponse<SoldierOuterLoginAccountDTO> getSshAccount() {
        SessionSoldier sessionSoldier = RpcContextUtil.getSessionSoldier();
        BizCheckUtil.checkNotNull(sessionSoldier, "用户非法");

        BaseResponse<SoldierOuterLoginAccountDTO> soldierOuterLoginAccountBySoldierId = soldierConsumer.getSoldierOuterLoginAccountBySoldierId(sessionSoldier.getUserId());
        if (soldierOuterLoginAccountBySoldierId.getDto() != null) {
            if (BizCheckUtils.checkMobile(soldierOuterLoginAccountBySoldierId.getDto().getOuterSysNickName())
                    || "0000".equals(soldierOuterLoginAccountBySoldierId.getDto().getOuterSysCertNo())) {

                log.error("姓名为手机号或身份证为'0000'，需要登出：{}", JSON.toJSONString(soldierOuterLoginAccountBySoldierId.getDto()));
                final Integer affectNum = cacheClient.remove(CommonConstant.CACHE_KEY_PREFIX_SESSION + sessionSoldier.getAuthorization(),
                        UserTypeEnum.SOLDIER, sessionSoldier.getUserId());
                throw new BizException(ErrorCodeEnum.ERROR_ALI_REAL_NAME);
            }
        }

        return soldierOuterLoginAccountBySoldierId;    }

}
